<template>
  <div>
    <el-form class="" :inline="true" :model="ruleForm">
      <el-form-item label="用户">
        <el-input
          style="width: 200px"
          placeholder="请输入用户名、ID、手机号"
          @change="start"
          v-model="like"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="团队">
        <el-select
          style="width: 180px"
          clearable
          v-model="formquery._include!.teamid"
          placeholder="团队"
          :remote-method="(query: string) => $store.dispatch('actionteam', { _like: ['name', query], tenant_id })"
          filterable
          remote
        >
          <el-option
            v-for="(k, i) in getteam"
            :key="i"
            :label="k.name"
            :value="Number(k.ID)"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="createdAt"
          type="daterange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :shortcuts="shortcuts"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="登录时间">
        <el-date-picker
          v-model="lasttime"
          type="daterange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :shortcuts="shortcuts"
        ></el-date-picker>
      </el-form-item>
    </el-form>
    <div class="row mb-1">
      <div class="col">
        <el-button @click="start" type="primary">查询</el-button>
        <el-button @click="addUser" type="primary">+ 添加用户</el-button>
        <el-button @click="addUserListDialogVisible = true" type="primary"
          >+ 批量添加</el-button
        >
      </div>
    </div>
    <div
      v-if="selectarr"
      v-show="handleSelectionChange"
      class="row selecttable mb-1"
    >
      <div>
        <el-tag
          :key="v.ID"
          v-for="(v, i) in selectarr"
          closable
          :disable-transitions="false"
          @close="handleClose(i)"
        >
          {{ v.name ? v.name : v.ID }}
        </el-tag>
      </div>
    </div>
    <el-table
      class="margin-top20"
      ref="multipleTable"
      border
      :data="tableData"
      height="74vh"
      style="width: 100%"
      @sort-change="sortchange"
      @cell-click="userhandleCurrentChange ? () => {} : handleClick"
      @selection-change="(d) => handleChange(d)"
      :highlight-current-row="!!userhandleCurrentChange"
      @current-change="userCurrentChange"
    >
      <el-table-column
        v-if="handleSelectionChange"
        type="selection"
        width="55"
      ></el-table-column>
      <el-table-column
        v-for="v in tableattr"
        :key="v.prop"
        :prop="v.prop"
        :label="v.label"
        :formatter="v.formatter"
        :sortable="v.sortable"
      ></el-table-column>
      <el-table-column prop="name" label="答题正确率" width="100">
        <template #default="scope">
          {{
            scope.row.userquestionaccount
              ? Math.floor(
                  (scope.row.userquestionaccount /
                    scope.row.userquestioncount) *
                    100
                )
              : 0
          }}
        </template>
      </el-table-column>
      <el-table-column prop="userquestioncount" label="答题次数" width="100">
      </el-table-column>
      <el-table-column
        prop=""
        :formatter="({ teamuser = [] }) => teamuser.map((e: any) => e.team.name).join(',')"
        label="所在团队"
        min-width="100"
      >
        <template #default="{ row }">
          <div style="display: flex; flex-wrap: wrap">
            <!-- 创建者 -->
            <!-- <el-tag type="success" class="question-intable-label" v-for="(v, k) in row.team" :key="v.ID">
							{{ v.name }}
						</el-tag> -->
            <div v-for="(v, k) in row.teamuser" :key="v.ID">
              <el-tag
                v-if="v?.team"
                type="primary"
                class="question-intable-label"
              >
                {{ v?.team?.name }}
              </el-tag>
            </div>
          </div>
          <!-- {{ row.team.map((e: any) => e.name).join(',') }}
          {{ row.teamuser.map((e: any) => e.team.name).join(',') }} -->
        </template>
      </el-table-column>
      <el-table-column prop="remarks" label="备注" width=""></el-table-column>
      <el-table-column
        v-if="!tenant_id"
        prop="tenant_id"
        label="tenant_id"
        width="100"
      ></el-table-column>
      <el-table-column prop="" label="操作" width="100">
        <template #default="scope">
          <el-button type="warning" @click="change(scope.row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="pager"
      @current-change="handleCurrentChange"
      :page-size="formquery._limit"
      :page-sizes="[20, 50, 100, 200, 300, 400, count]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="(e) => (formquery._limit = e)"
      :total="count"
    >
    </el-pagination>
    <!-- 添加、修改用户 -->
    <el-dialog
      :title="title"
      v-model="dialogVisible"
      width="650"
      @close="closeAddUserDialog"
    >
      <template #header>
        <span class="icon-text el-dialog__header-title">
          <el-icon class="text-primary">
            <Guide />
          </el-icon>
          {{ title }}
        </span>
      </template>
      <el-form :model="ruleForm" label-width="auto" class="demo-ruleForm">
        <el-form-item label="用户昵称">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="用户姓名">
          <el-input v-model="ruleForm.xingming"></el-input>
        </el-form-item>
        <el-form-item label="用户密码">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="用户手机号">
          <el-input v-model="ruleForm.phonenum"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="ruleForm.remarks"></el-input>
        </el-form-item>
        <el-form-item v-if="!tenant_id" label="组织(tenant_id)">
          <el-radio-group v-model="tenantId">
            <el-radio :value="0">官方</el-radio>
            <el-radio :value="'码客行'">码客行</el-radio>
            <el-radio :value="'新华书店'">新华书店</el-radio>
          </el-radio-group>
        </el-form-item>
        <div class="row">
          <div class="col text-right">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submit">确 定</el-button>
          </div>
        </div>
      </el-form>
    </el-dialog>
    <el-drawer
      class="my-el-drawer"
      size="1200px"
      append-to="#app"
      v-model="addUserListDialogVisible"
      title="批量添加"
      @close="closeDrawer"
    >
      <template #header="{ close, titleId, titleClass }">
        <span class="icon-text el-dialog__header-title">
          <el-icon class="text-primary">
            <Guide />
          </el-icon>
          <span :id="titleId" :class="titleClass">批量添加</span>
        </span>
      </template>
      <Addtable v-bind="{ close: isClosed, closeDrawer }" />
    </el-drawer>
  </div>
</template>
<script setup lang="ts">
import { ElMessage } from "element-plus";
import moment from "moment";
import { debounce, difference } from "underscore";
import { computed, inject, onMounted, reactive, ref, watch } from "vue";
import { useStore } from "vuex";
import {
  Iobj,
  asyncadmincreateorupdateuser,
  asyncadmingetuser,
} from "../../../api/index";
import { Storekey, TtableU } from "../../../interface";
import {
  default as Studycodemodel,
  default as study,
} from "../../../mysql_interface/studycodemodel";
import { modelFind } from "../../../util/modelkey";
import { toLocaleDateString } from "../../../util/time";
import Addtable from "./addtable.vue";

// 码客行
const tenant_id = inject<string | undefined>("tenant_id", undefined);

const shortcuts = [
  {
    text: "上周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "本周",
    value: () => {
      const end = new Date();
      const start = moment().day(1).unix() * 1000;
      return [start, end];
    },
  },
  {
    text: "本月",
    value: () => {
      const end = new Date();
      const start = moment().date(1).unix() * 1000;
      return [start, end];
    },
  },
  {
    text: "最近90天",
    value: () => {
      const end = new Date();
      const start = moment().date(-90).unix() * 1000;
      return [start, end];
    },
  },
];
const initialUserInfo = {
  ID: undefined,
  name: "",
  password: "000000",
  phonenum: "",
  remarks: "",
  // 其他需要初始化的字段...
};

const prop = defineProps<{
  tablekey?: Array<keyof study.Iuser>;
  handleSelectionChange?: (n: study.Iuser[]) => void;
  selectarr?: study.Iuser[];
  userhandleCurrentChange?: (n: study.Iuser) => void;
}>();

const store = useStore(Storekey);
const tableData = computed(() => {
  return store.state.users?.rows || [];
});
const count = computed(() => {
  return store.state.users?.count || 0;
});
const getteam = computed(() => {
  return store.state.team?.rows || [];
});

// 增加、修改弹窗
const title = ref("添加成员");
const dialogVisible = ref(false);
const ruleForm = ref<study.Iuser>(initialUserInfo);
function addUser() {
  dialogVisible.value = true;
  title.value = "添加成员";
}

const tenantId = computed({
  set(v) {
    if (ruleForm.value) {
      (ruleForm.value.tenant_id as any) = v === 0 ? null : v;
      console.log("ruleForm.value=>", ruleForm.value?.tenant_id);
    }
  },
  get() {
    return ruleForm.value.tenant_id === null ? 0 : ruleForm.value.tenant_id;
  },
});
async function change(row: Studycodemodel.Iuser) {
  title.value = `修改-${row.name}`;
  ruleForm.value = await asyncadmingetuser(row);
  dialogVisible.value = true;
}
async function submit() {
  try {
    let data = ruleForm.value;
    data = { ...ruleForm.value, tenant_id };
    await asyncadmincreateorupdateuser(data);
    ElMessage({ message: "操作成功", type: "success" });
    start();
    dialogVisible.value = false;
  } catch (e: any) {
    ElMessage({ message: e, type: "error" });
  }
}
function resetAddUserForm() {
  Object.assign(ruleForm.value, initialUserInfo);
}
function closeAddUserDialog() {
  resetAddUserForm(); // 重置 userinfo
}

onMounted(() => {
  start();
  const table: any = multipleTable.value;
  for (const v of tableData.value) {
    const d = prop.selectarr?.find((e) => e.ID === v.ID);
    if (d) {
      porparr.value.push(d);
      table.toggleRowSelection(v, true);
    } else {
      table.toggleRowSelection(v, false);
    }
  }
});

const like = ref();
const createdAt = ref([]);
const lasttime = ref([]);
const formquery = reactive<Iobj<study.Iuser>>({
  _limit: 20,
  _offset: 0,
  _order: "ID",
  _include: {},
});
watch(formquery, () => {
  start();
});

const porparr = ref<Studycodemodel.Iuser[]>([]);
const multipleTable = ref();
watch(
  () => prop.selectarr,
  () => {
    porparr.value = [];
    for (const v of tableData.value) {
      const d = prop.selectarr?.find((e) => e.ID === v.ID);
      if (d) {
        porparr.value.push(d);
        multipleTable.value?.toggleRowSelection(v, true);
      } else {
        multipleTable.value?.toggleRowSelection(v, false);
      }
    }
  }
);
async function start() {
  const { _limit, _offset, _order, _sortable, _include = {} } = formquery;
  porparr.value = [];
  try {
    const t: Iobj<Studycodemodel.Iuser> = {
      _limit: _limit,
      _offset: _offset,
      _order: _order,
      _sortable: _sortable,
      _include: {},
      // 码客行
      tenant_id,
    };
    if (like.value) {
      t._like = [
        ["ID", like.value],
        ["name", like.value],
        ["remarks", like.value],
        ["phonenum", like.value],
        ["gid", like.value],
      ];
    }
    if (!_order) {
      delete t._sortable;
      delete t._order;
    }
    if (createdAt.value && createdAt.value.length) {
      t.createdAt = {
        lt: createdAt.value[1],
        gt: createdAt.value[0],
      };
    }
    if (lasttime.value && lasttime.value.length) {
      t.lasttime = {
        lt: lasttime.value[1],
        gt: lasttime.value[0],
      };
    }
    if (_include && _include.teamid && t._include) {
      t._include.teamuser = ["teamid", _include.teamid];
    }
    await store.dispatch("actionusers", t);
  } catch (e: any) {
    ElMessage.error(e);
  }
}
const handleChange = debounce(_handleChange, 300);
const _tableattr: Array<TtableU<study.Iuser>> = [
  { prop: "ID", label: "用户id", sortable: true },
  { prop: "name", label: "用户昵称", sortable: true },
  { prop: "xingming", label: "姓名" },
  {
    prop: "createdAt",
    label: "创建时间",
    sortable: true,
    formatter: ({ createdAt }) => formatter({ updatedAt: createdAt }),
  },
  {
    prop: "lasttime",
    label: "上次登录时间",
    sortable: true,
    formatter: ({ lasttime }) => formatter({ updatedAt: lasttime }),
  },
  {
    prop: "userquestiontime",
    label: "最近做题时间",
    formatter: ({ userquestiontime }) =>
      formatter({ updatedAt: userquestiontime }),
  },
];
const tableattr = ref<TtableU<Studycodemodel.Iuser>[]>(
  modelFind(_tableattr, prop.tablekey)
);

function handleClick(row: Studycodemodel.Iuser) {}

function sortchange(row: { prop: any; order: any }) {
  const { prop, order } = row;
  if (order == "descending") {
    formquery._sortable = "DESC";
  } else {
    formquery._sortable = "ASC";
  }
  formquery._order = prop;
  start();
}
const formatter = (data: Studycodemodel.Iuser) =>
  toLocaleDateString(data.updatedAt);
function handleCurrentChange(val: number) {
  formquery._offset = Number(formquery._limit) * (val - 1);
}
function _handleChange(data: study.Iuser[]) {
  if (prop.handleSelectionChange) {
    // 查找要添加的
    const datanum = data.map((v) => v.ID);
    const _porparr = porparr.value.map((v) => v.ID);
    const add = difference(datanum, _porparr);
    // 查找要删除的
    const out = difference(_porparr, datanum);
    const _data = prop.selectarr?.map((v) => v) || [];
    for (let v of add) {
      const e = tableData.value.find(({ ID }) => ID === v);
      if (e) {
        _data.push(e);
      }
    }
    for (let v of out) {
      const index = _data.findIndex(({ ID }) => v === ID);
      _data.splice(index, 1);
    }
    if (out.length || add.length) {
      prop.handleSelectionChange(_data);
    }
  }
}
function handleClose(v: number) {
  const data: study.Iuser[] = [];
  if (prop.handleSelectionChange && prop.selectarr) {
    prop.selectarr.forEach((vo, i) => {
      if (i !== v) {
        data.push(vo);
      }
    });
    prop.handleSelectionChange(data);
  }
}
// (currentRow: any, oldCurrentRow: any)
function userCurrentChange(data: study.Iuser) {
  if (prop.userhandleCurrentChange) prop.userhandleCurrentChange(data);
}

// 批量添加
const addUserListDialogVisible = ref(false);
const isClosed = ref(false);
watch(
  () => addUserListDialogVisible.value,
  (v) => {
    isClosed.value = v;
  }
);
function closeDrawer() {
  addUserListDialogVisible.value = false;
  store.state.socket.removeListener("api_import_user");
}
</script>

<style scoped>
.selecttable {
  height: 80px;
  overflow: auto;
}
</style>
